home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5767 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  57 lines

  1. Newsgroups: comp.lang.c
  2. Path: tank.news.pipex.net!pipex!warwick!bsmail!talisker!nathan
  3. From: nathan@pact.srf.ac.uk (Nathan Sidwell)
  4. Subject: Re: Optimization Q: for( i=0; i<SIZE/2; i++) ??
  5. Message-ID: <Dn2nKB.C1@uns.bris.ac.uk>
  6. Sender: usenet@uns.bris.ac.uk (Usenet news owner)
  7. Nntp-Posting-Host: talisker.pact.srf.ac.uk
  8. Organization: Inmos
  9. X-Newsreader: TIN [version 1.2 PL2]
  10. References: <4g1j9n$ooe@news.csus.edu>
  11. Date: Tue, 20 Feb 1996 11:21:47 GMT
  12.  
  13. Jerry Leong (wleong@sfsu.edu) wrote:
  14.  
  15. : This question has been bothering me for quite a while now.
  16.  
  17. : If I have the following for loop,
  18. :         for( i=0; i< SIZE/2 ; i++).....
  19. : Will the code execute faster if I precompute SIZE/2 before hand and
  20. : do this
  21. :       k = SIZE/2;
  22. :        for(i=0; i<k ; i++).....
  23.  
  24. : How does this work? I mean, would SIZE/2 get computed everytime during
  25. : the for loop, or it simply caculated once?
  26. It depends on
  27. a)what SIZE is
  28. b)your compiler
  29. c)the optimization level
  30.  
  31. If SIZE is a simple #define, then the value of the expression 'SIZE/2'
  32. can be determined at compile time. This is called constant folding.
  33.  
  34. Any modern complier, at its lowest, non-zero, level of optimization (ie
  35. -O1 or more), should work this out. so the code should compile to
  36. something like
  37.  
  38. compareless <ctemp>,<i>,<SIZE/2>
  39. jumpnotzero <ctemp>,label
  40.  
  41. If SIZE is not evaluable at compile time, then a compiler might be
  42. able to determine that the value of 'SIZE/2' does not change with loop
  43. iterations. It could then hoist the evaluation out of the loop, and
  44. therefore only do it once.
  45.  
  46. Now, writing the loop as
  47. for(ix = SIZE/2; ix--;)
  48.  ...
  49. might make a (small) difference.
  50.  
  51. nathan
  52. --
  53. Nathan Sidwell                         Holder of the Xmris home page
  54. Chameleon Architecture Group at SGS-Thomson, formerly Inmos
  55. http://www.pact.srf.ac.uk/~nathan/                  Tel 0117 9707182
  56. nathan@inmos.co.uk or nathan@bristol.st.com or nathan@pact.srf.ac.uk
  57.